import React, { memo, useState ,useEffect} from "react";
// antd
import { Upload, message } from "antd";
// icon
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
// api
import { UploadToken } from "services/common";
import storage from "../../utils/storage";

interface Props {
  name?: string;
  style?: object;
  [propName: string]: any;
}
const HYUploadComp = memo(function (props: Props) {
  // state 
  const [loading, setLoading] = useState(false);
  const [uploadKey, setUploadKey] = useState({
    token: "",
    key: "",
  });
  const [imageUrl, setImageUrl] = useState("");
  //   const name = props.name;

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
    // 生命周期 
    useEffect(() => {
      
      return () => {
        storage?.remove?.('UploadToken')
      }
    }, [])

  // 方法 
  const getUploadToken = () => {
    return UploadToken({
      ak: "dfawTwXxmuWJywb6LFiAn1a_xU8qz58dl3v7Bp74",
      sk: "gynIo9E-zyKeKBrPqeWmmgeA4DQSsl8gpuyYl9dT",
      buckety: "bigbigtime",
    }).then((response: any) => {
      const data = response.data;
      //   localStorage.setItem("UploadToken", data.token);
      storage?.set?.("UploadToken", data.token);
      return data.token;
    });
  };
  // 图片转base64
  //   const getBase64 = (img: any, callback: any) => {
  //     const reader = new FileReader();
  //     reader.addEventListener("load", () => callback(reader.result));
  //     reader.readAsDataURL(img);
  //   };
  const beforeUpload = (file: any) => {
    let token = storage?.get?.("UploadToken");
    if (!token) {
      getUploadToken().then((res) => {
        token = res.data;
      });
    } // 等待某些行为执行完成，表面性的理解

    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    // 解析文件
    const name = file.name;
    const key = encodeURI(`${name}`);
    // 更新文件的 key
    const tokens = token as string;
    setUploadKey(() => {
      console.log(tokens, key);
      return { ...uploadKey, token: tokens, key };
    });
    return isJpgOrPng && isLt2M;
  };
  // 选择图片时
  const handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      const fileInfo = info.file.response;
      const imageUrl = `http://qkronr45u.hn-bkt.clouddn.com/${fileInfo.key}`;
      setImageUrl(imageUrl);
      setLoading(false);
      triggerChange(imageUrl);
    }
  };
  const triggerChange = (url: string) => {
    const onChange = props.onChange;
    if (onChange) {
      onChange(url);
    }
  };

  return (
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      data={uploadKey}
      action="https://up-z2.qiniup.com"
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img src={imageUrl} alt="avatar" style={{ width: "100%" }} />
      ) : (
        uploadButton
      )}
    </Upload>
  );
});

export default HYUploadComp;
